﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace MyAMS.WebServer.Models.Extensions
{
    /// <summary>
    /// 节点扩展
    /// </summary>
    public static class NodeExtensions
    {
        /// <summary>
        /// 根据节点名称获取指定的子节点
        /// </summary>
        /// <param name="node">父节点</param>
        /// <param name="name">节点名称</param>
        /// <returns>子节点</returns>
        public static Node GetNode(this Node node, string name)
        {
            return (from n in node.Children
                    where n is Node && String.Compare(n.Name, name, true) == 0
                    select n as Node).SingleOrDefault();
        }

        /// <summary>
        /// 根据节点名称获取指定的数据
        /// </summary>
        /// <param name="node">父节点</param>
        /// <param name="name">数据名称</param>
        /// <returns>数据</returns>
        public static Archive GetArchive(this Node node, string name)
        {
            return (from n in node.Children
                    where n is Archive && String.Compare(n.Name, name, true) == 0
                    select n as Archive).SingleOrDefault();
        }

        /// <summary>
        /// 获取特定节点的路由规则
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="area">规则区域</param>
        /// <returns>路由规则</returns>
        public static IEnumerable<RoutingRole> GetRoles(this BaseNode node, string area)
        {
            return from r in node.RoutingRoles
                   where String.Compare(r.Area, area, false) == 0
                   orderby r.IsDynamicRole()
                   select r;
        }

        /// <summary>
        /// 获取特定节点的所有继承的路由规则
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="area">规则区域</param>
        /// <param name="hasOwner">是否被拥有</param>
        /// <returns>路由规则</returns>
        public static List<RoutingRole> GetRolesWithInheritance(this BaseNode node, string area, bool hasOwner)
        {
            IEnumerable<RoutingRole> parentRoles = node.Parent == null ? Enumerable.Empty<RoutingRole>()
                    : hasOwner ?
                    from r in node.Parent.GetRolesWithInheritance(area, hasOwner)
                    where r.InheritanceType == RoutingRoleInheritance.Enabled
                    select r :
                    from r in node.Parent.GetRolesWithInheritance(area, hasOwner)
                    where r.InheritanceType != RoutingRoleInheritance.None
                    select r;
            List<RoutingRole> currentRoles = new List<RoutingRole>(node.GetRoles(area));
            currentRoles.AddRange(parentRoles);
            return currentRoles;
        }
    }
}
